package com.bookstore.servlet;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/client/user.do")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //1.从前端获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.根据用户名和密码 创建一个 User 对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //3.将 User 对象 传给 userService
        User login = userService.login(user);
        //4.根据返回值 判断是否登录成功
        if (login == null) {
            writer.write("<h1>登录失败</h1>");
        } else {
            writer.write("<h1>登录成功</h1>");
        }
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //防止中文乱码
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //从前端请求中，获取到需要的用户信息
        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String telephone = req.getParameter("telephone");
        String gender = req.getParameter("gender");
        String introduce = req.getParameter("introduce");
        //根据前端传来的信息 创建一个user对象
        User user = new User(null, username, password, gender, email, telephone, introduce, null, null, null, null);
        //传入到注册方法中
        int result = userService.registUser(user);
        //根据受影响的行数 判断是否注册成功
        if (result == 1) {
            writer.write("<h1>注册成功</h1>");
        } else {
            writer.write("<h1>注册失败</h1>");
        }
    }

    protected void isExists(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        //判断用户名是否已注册 flag == true 已经注册
        boolean flag = userService.existsUsername(username);
        PrintWriter writer = resp.getWriter();
        if (flag) {
            //如果用户名已存在
            writer.write("true");
        }
    }
}
